<?php
/**
 * Created by PhpStorm.
 * User: denh
 * Date: 16/5/17
 * Time: 下午2:17
 */
//最美医生投票--wym
class VoteController extends BaseController {
    function __construct($m = DEFAULT_CONTROLLER, $a = DEFAULT_METHOD) {
        parent::__construct($m, $a);
        //$this->redirectToWeixinForOpenid();
    }

    //最美儿医主页程序；第一版
    function index1()
    {
        if(isset($_GET['id'])){
            $where = 'name != "" and id !='.$_GET['id'];
        }else{
            $where = 'name != ""';
        }
        require_once ROOT_PATH . 'tools/tools.tongji.php';
        $do_db = new DoVote_beautiful_doctor();
        $do_record = new DoVote_record();
        $now_time = date('Y-m-d',time());
        $where1 = "vote_openId = '{$this->openId()}' and  date_format(vote_time,'%Y-%m-%d') =  '{$now_time}'";
        $vote_re_id = "";
        //投票记录表-判断用户是否已经投票，当前被投票医师，当前投票人，当前时间（今天内）
        $record_list = $do_record->fields('bd_id')->where($where1)->rows();
        foreach($record_list as $k =>$v){
            $vote_re_id.=$v['bd_id']."-";
        }
        $vote_id = "";
        $db_list = $do_db->rows();
        foreach($db_list as $k =>$v){
            $vote_id.=$v['id']."-";
        }

        $do_db->set_id($_GET['id']);
        $dc_detail = $do_db->where($do_db->data)->row();
        $cont = $this->replacePicUrl($dc_detail->data['descript_story'],G_SITE_CDN);

        if($dc_detail){
           $do_db->set_look_num($do_db->get_look_num() + 1);
           $do_db->save();
            $title = "今日最美儿科医生—— ".$dc_detail->data['name'];
            $img = G_SITE_CDN."/".$dc_detail->data['head_img'];
            $url = '';
        }else{
            $title = "爱贝儿医美赞臣“最美儿科医生”震撼来袭";
            $img = G_SITE_CDN."/business/style/bd_doctor.jpg";
            $url = 'http://d.eqxiu.com/s/d2Ykzt3m';
        }

        $vote_list = $do_db->where($where)->orderby("id desc")->rows();
        $ajax_vote_url = $this->url('vote','ajax_vote');
        $vote_index_url = $this->url('vote','index1');
        $vote_recommend_url = $this->url('vote','recommend_doctor');
        $vote_leave_url = $this->url('vote','vote_leave');
        $tongjiUrl = _cnzzTrackPageView(1259747134);

        require $this->template;
    }

    //最美儿医主页程序；第二版
    function index2(){
        if(isset($_GET['id'])){
            $where = "name != '' and name!='杜敏联' and id !=".$_GET['id'];
        }else{
            $where = 'name != "" and name!="杜敏联"';
        }
        require_once ROOT_PATH . 'tools/tools.tongji.php';


        $do_db = new DoVote_beautiful_doctor();
        $do_record = new DoVote_record();
        $now_time = date('Y-m-d',time());
        //投票条件：投票状态不为空 vote_state is not null
        $where1 = "vote_openId = '{$this->openId()}' and  date_format(vote_time,'%Y-%m-%d') =  '{$now_time}' and  vote_state !=0";
        $vote_re_id = "";//记录表所有id
        //投票记录表-判断用户是否已经投票，当前被投票医师，当前投票人，当前时间（今天内）
        $record_list = $do_record->fields('id,bd_id')->where($where1)->rows();


        foreach($record_list as $k =>$v){
            $caches = '1';
            $vote_re_id.=$v['bd_id']."-";
        }
        $Bd_id = "";
        $db_list = $do_db->rows();
        foreach($db_list as $k =>$v){
            $Bd_id.=$v['id']."-";//最美所有id
        }
        //用户状态

        $user_state = $this->vote_user();

        if($user_state=='注册') {
            $user_url = $this->url('user', 'user_register');
        } else if($user_state=='认证'){
            $user_url = $this->url('user','user_base');
        }
        //判断待认证用户是否已经认证，并修改其投票的有效性,2是已认证用户投票状态
        $whereRenzhen = "vote_openId = '{$this->openId()}' and  vote_state =1" ;
        $recordRenzhen = $do_record->fields('id,bd_id')->where($whereRenzhen)->rows();

        foreach($recordRenzhen as $k =>$v){
            if($user_state == '已认证'){
                $do_record->set_id($v['id']);
                $do_record->set_vote_state('2');
                $do_record->set_vote_openId($this->openId());
                if($do_record->save()){
                    $do_db->fields('vote_num')->row($v['bd_id']);
                    $do_db->set_id($v['bd_id']);
                    $do_db->set_vote_num($do_db->get_vote_num()+1);
                    $do_db->save();

                }
            }

        }
        //判断待认证用户是否已经认证--end
        $arr = array('id'=>$_GET['id']);
        $dc_detail = $do_db->where($arr)->row();

        //投票详情医师，已投票人信息
        if($dc_detail){
            $record_my = $do_record->fields('vote_name, vote_img, count(vote_openId) nums')->where('bd_id='.$_GET['id']." and vote_name !='' and vote_state !=0")->orderby("id desc")->groupby('vote_openId')->rows();
            $dc_detail->data['voteUsers'] = $record_my;
            $do_db->set_look_num($do_db->get_look_num() + 1);
            $do_db->save();

            $title = "今日最美儿科医生—— ".$dc_detail->data['name'];
            $img = G_SITE_CDN."/".$dc_detail->data['head_img'];
            $url = '';
        }else{
            $title = "爱贝儿医美赞臣“最美儿科医生”震撼来袭";
            $img = G_SITE_CDN."business/style/vote/style/vote32.png";
            $url = 'http://d.eqxiu.com/s/d2Ykzt3m';
        }

        $vote_list = $do_db->where($where)->orderby("vote_num desc")->rows();
        foreach($vote_list as $k =>$v){
            // and vote_state !=0 上线where 条件必填
            $record_user_list = $do_record->fields('vote_name, vote_img, count(vote_openId) nums')->where('bd_id='.$v['id']." and vote_name !='' and vote_state !=0")->orderby("id desc")->groupby('vote_openId')->limit(6)->rows();
            $vote_list[$k]['voteUsersCount'] = $do_record->fields('*')->groupby('')->count();
            $vote_list[$k]['voteUsers'] =$record_user_list;
        }

        $vote_recommend_url = $this->url('vote','recommend_doctor');
        $vote_index_url = $this->url('vote','index');
        $vote_act = $this->url('vote','act');

        require $this->template;
    }

    function zhibo() {
        $account = $this->request('account');
        $token = $this->request('token');
        if (!$account or !$token) {
            $this->redirectToWeixinForOpenid();
            $token = $_SESSION['userCenter']['token'];
            $account = $_SESSION['userCenter']['id'];
        }
        if ($token) {
            $url = sprintf('http://cdnapph5.babydr.cn/html/beautifulDoctorVideo.html?token=%s&account=%s', $token, $account);
            header("Location:$url");
        }
    }

    function index(){
        $time= date('Y-m-d H:i:s',time());
        $account = $this->request('account');
        $token = $this->request('token');

        //$time >= '2016-10-22 18:30:00'
        $this->redirect('vote','vote_end', array('account'=>$account, 'token'=>$token));
        die;
        if ($time >= '2016-10-22 13:35:00') {
            $this->zhibo();
            die;
        } else if ($time >= '2016-10-16 00:00:00') {
            $this->redirect('vote','vote_end', array('account'=>$account, 'token'=>$token));
            die;
        }
        $id = $_GET['id'];
        if(isset($_GET['id'])){
            $where = "name != '' and name!='杜敏联' and id !=".$_GET['id'];
        }else{
            $where = 'name != "" and name!="杜敏联"';
        }
        $do_db = new DoVote_beautiful_doctor();
        $do_record = new DoVote_record();
        $now_time = date('Y-m-d',time());
        //投票条件：投票状态不为空 vote_state is not null
        $where1 = "vote_openId = '{$this->openId()}' and  date_format(vote_time,'%Y-%m-%d') =  '{$now_time}' and  vote_state !=0";
        $vote_re_id = "";//记录表所有id
        //投票记录表-判断用户是否已经投票，当前被投票医师，当前投票人，当前时间（今天内）
        $record_list = $do_record->fields('id,bd_id')->where($where1)->rows();
        foreach($record_list as $k =>$v){
            $caches = '1';
            $vote_re_id.=$v['bd_id']."-";
        }
        $Bd_id = "";
        $db_list = $do_db->rows();
        foreach($db_list as $k =>$v){
            $Bd_id.=$v['id']."-";//最美所有id
        }
        //用户状态
        $user_state = $this->vote_user();

        if($user_state=='注册') {
            $user_url = $this->url('user', 'user_register');
        } else if($user_state=='认证' || $user_state=='已认证'){
            $user_url = $this->url('user','user_base');
        }
        //判断待认证用户是否已经认证，并修改其投票的有效性,2是已认证用户投票状态
        $whereRenzhen = "vote_openId = '{$this->openId()}' and  vote_state =1" ;
        $recordRenzhen = $do_record->fields('id,bd_id')->where($whereRenzhen)->rows();

        foreach($recordRenzhen as $k =>$v){
            if($user_state == '已认证'){
                $do_record->set_id($v['id']);
                $do_record->set_vote_state('2');
                $do_record->set_vote_openId($this->openId());
                if($do_record->save()){
                    $do_db->fields('vote_num')->row($v['bd_id']);
                    $do_db->set_id($v['bd_id']);
                    $do_db->set_vote_num($do_db->get_vote_num()+10);
                    $do_db->save();

                }
            }

        }
        $vote_list = $do_db->fields('id,name,hospital,keshi,vote_num,head_img')->where($where)->orderby("vote_num desc")->rows();
        $vote_recommend_url = $this->url('vote','recommend_doctor');
        $vote_index_url = $this->url('vote','index');
        $vote_act = $this->url('vote','act');
        $vote_detail = $this->url('vote','detail');
        require_once ROOT_PATH . 'tools/tools.tongji.php';
        require $this->template;
    }

    //用户详情
    function detail(){
        $id = $this->request('id','',true);
        $do_db = new DoVote_beautiful_doctor();
        $dc_detail = $do_db->row($id);
        $do_record = new DoVote_record();
        $now_time = date('Y-m-d',time());
        //投票条件：投票状态不为空 vote_state is not null
        $where1 = "vote_openId = '{$this->openId()}' and  date_format(vote_time,'%Y-%m-%d') =  '{$now_time}' and  vote_state !=0";
        $vote_re_id = "";//记录表所有id
        //投票记录表-判断用户是否已经投票，当前被投票医师，当前投票人，当前时间（今天内）
        $record_list = $do_record->fields('id,bd_id')->where($where1)->rows();
        foreach($record_list as $k =>$v){

            $vote_re_id.=$v['bd_id']."-";
        }
        //用户状态
        $user_state = $this->vote_user();

        if($user_state=='注册') {
            $user_url = $this->url('user', 'user_register');
        } else if($user_state=='认证'){
            $user_url = $this->url('user','user_base');
        }
        $vote_act = $this->url('vote','act');
        $vote_recommend_url = $this->url('vote','recommend_doctor');
        require $this->template;
    }


    //点击投票判断-第二版
    //用户状态
    function ajax_vote_new(){
        if (!$this->openId()) {
            exit('no');
        }
        $do_db = new DoVote_beautiful_doctor();
        $do_record = new DoVote_record();
        $do_user = new Do用户();

        $now_time = date('Y-m-d', time());
        $do_db->set_id($this->request('id',"",true));
        $do_user->set_openID($this->openId());
        $do_record->set_vote_openId($this->openId());
        $db_res = $do_db->where($do_db->data)->row();
        if(!$db_res){
            $this->jsonOutPut('-1','投票失败！');
        }
        //投票条件验证--每天一个人投一个最美儿医-
        $where = "bd_id ={$_POST['id']} and vote_openId = '{$this->openId()}' and  date_format(vote_time,'%Y-%m-%d') =  '{$now_time}' and vote_state !=0 ";

        //判断投票用户是否为已关注用户,如果是，将获取他的name和头像
        $oneself = $do_user->where($do_user->data)->row();
        //判断用户是否已经投票，当前被投票医师，当前投票人，当前时间（今天内）
        $count_record = $do_record->where($where)->count();

        if ($count_record>=1) {
           $this->jsonOutPut('-1','已经投过票');
        } else {
            if ($oneself->data) {
                $do_record->set_vote_img($oneself->data['头像']);
                $do_record->set_vote_name($oneself->data['name']);
            }
            $do_record->set_bd_id($_POST['id']);
            $do_record->set_vote_openId($this->openId());
            $do_record->set_vote_time(date('Y-m-d H:i:s', time()));
            $do_record->set_vote_ip(Tools::getIP());
            $do_record->set_http_user_agent($_SERVER['HTTP_USER_AGENT']);
            $do_record->set_vote_state($_POST['userState']);
            if ($do_record->save()) {
                if($_POST['userState']==2){
                    $do_db->set_vote_num($do_db->get_vote_num() + 10);
                    $do_db->save();
                }
            }
            $this->jsonOutPut('0',$do_db->get_vote_num());

        }

    }

    //第二版本投票主页 判断用户身份
    function vote_user(){
        $do_user = new Do用户();
        $do_doc = new Do医师详情();
        $openid = $this->openId();
        $do_user->set_openID($openid);
        $do_user->fields('id,密码,认证')->where($do_user->data)->row();

        if ($do_user->get_密码() == "") {
            return '注册';

        }
        $do_doc->set_用户id($do_user->get_id());
        $where = '用户id='.$do_user->get_id().' and name  is not null';
        $res = $do_doc->where($where)->row();

        if (!$res) {
            return '认证';

        }
        //认证期间用户
        if(($do_user->get_认证()==1 || $do_user->get_认证()==""||$do_user->get_认证()==="")&& $res){
            return '认证中';
        }
        return '已认证';

    }

    //推荐医师
    function recommend_doctor(){
        $do_re = new DoVote_recommend_doctor();
        if ($_POST) {
            $do_re->set_dc_name($this->request('dc_name'));
            $do_re->set_dc_tel($this->request('dc_tel'));
            $do_re->set_dc_descript($this->request('dc_descript'));
            $do_re->set_referrer_tel($this->request('referer_tel'));
            $do_re->set_state('待审核');
            $do_re->set_referrer($this->request('referer'));
            $do_re->set_time(date('Y-m-d H:i:s',time()));
            if($do_re->save()){
                echo "<script>alert('我们已获知您的推荐信息');location.href='http://x.eqxiu.com/s/d2Ykzt3m';</script>";
            }else{
                echo "<script>alert('很遗憾您的推荐失败！待会再试吧！');location.replace(location);</script>";
            }

        } else {
            require $this->template;
        }

    }

    //ajax 请求处理投票--第一版本投票规则
    function ajax_vote(){
        if (!$this->openId()) {
            exit('no');
        }
        $do_db = new DoVote_beautiful_doctor();
        $do_record = new DoVote_record();
        $do_user = new Do用户();

        $now_time = date('Y-m-d', time());
        $do_db->set_id($this->request('id',"",true));
        $do_user->set_openID($this->openId());
        $do_record->set_vote_openId($this->openId());
        $db_res = $do_db->where($do_db->data)->row();
        if(!$db_res) {
            echo "no_id";
            exit;
        }

        //当天投票条件验证
        $where = "bd_id ={$_POST['id']} and vote_openId = '{$this->openId()}' and  date_format(vote_time,'%Y-%m-%d') =  '{$now_time}'";
        //活动累计投票数条件
        $where1 = "bd_id ={$_POST['id']} and vote_openId = '{$this->openId()}'";
        //判断投票用户是否为已关注用户,如果是，将获取他的name和头像
        $oneself = $do_user->where($do_user->data)->row();
        //判断用户是否已经投票，当前被投票医师，当前投票人，当前时间（今天内）
        $count_record = $do_record->where($where)->count();
        //累计投票--10票
        $count_record_total = $do_record->where($where1)->count();
        if( $count_record_total>=10){
            echo "beyond";
        }else{
            if ($count_record>=1) {
                echo "no";
            } else {
                if ($oneself->data) {
                    $do_record->set_vote_img($oneself->data['头像']);
                    $do_record->set_vote_name($oneself->data['name']);
                }
                $do_record->set_bd_id($_POST['id']);
                $do_record->set_vote_openId($this->openId());
                $do_record->set_vote_time(date('Y-m-d H:i:s', time()));
                $do_record->set_vote_ip(Tools::getIP());
                $do_record->set_http_user_agent($_SERVER['HTTP_USER_AGENT']);
                if ($do_record->save()) {
                    $do_db->set_vote_num($do_db->get_vote_num() + 1);
                    $do_db->save();
                }
                echo $do_db->get_vote_num();
            }
        }
    }


    //投票留言
    function vote_leave(){
        if(empty($_POST['bd_id']))  {
            exit;
        }
        if($_POST){
            $do_leave = new DoVote_leave_words();
            $do_leave->set_bd_id($this->request('bd_id',"",true));
            $do_leave->set_user_status($this->request('people'));
            $do_leave->set_content($this->request('content'));
            $do_leave->set_tel($this->request('tel',"",true));
            $do_leave->set_time(date('Y-m-d H:i:s',time()));
            $index_url = $this->url('vote','index',array('id'=>$_POST['bd_id']));
            if($do_leave->save()){
                $this->successPage('留言成功',$index_url);
            }else{
                $this->errorPage('留言失败');
            }
        }


    }

    function newest_beautiful_doctor() {
        #$doVote = new DoVote_beautiful_doctor();
        #$id = $doVote->fields("max(id)")->getOneField();
        $this->redirect("vote", "index");
    }

    /**
     * 替换编辑器内容中的图片 添加域名
     * @param  string $content 要替换的内容
     * @param  string $strUrl 内容中图片要加的域名
     * @return string
     * @eg
     */
    function replacePicUrl($content = null, $strUrl = null) {
        if ($strUrl) {
            //提取图片路径的src的正则表达式 并把结果存入$matches中
            preg_match_all('/<img.*?src="(.*?)".*?>/is',$content,$matches);
            $img = "";
            //注意，上面的正则表达式说明src的值是放在数组的第二个中
            $img = $matches[1];
            $patterns= array();
            $replacements = array();
            foreach($img as $imgItem){
               if(!strstr($imgItem,'http')){
                   $final_imgUrl = $strUrl.$imgItem;
                   $replacements[] = $final_imgUrl;
                   $img_new = "/".preg_replace("/\//i","\/",$imgItem)."/";
                   $patterns[] = $img_new;
               }

            }

            //让数组按照key来排序
            ksort($patterns);
            ksort($replacements);

            //替换内容
            $vote_content = preg_replace($patterns, $replacements, $content);
            return $vote_content;

        } else {
            return $content;
        }
    }

    //最美儿医第二版-活动规则
    function act(){
        require $this->template;
    }

    //结束页面倒计时
    function vote_end(){
        $account = $this->request('account');
        $token = $this->request('token');

        $time = strtotime('2016-10-22 13:35:00');
        $nowTime = time();
        if ($account and $token) {
            $index_url = sprintf('http://cdnapph5.babydr.cn/html/beautifulDoctorVideo.html?token=%s&account=%s', $token, $account);
        } else {
            $index_url = $this->url('vote','zhibo', array('account'=>$account, 'token'=>$token));
        }
        $share_url = $this->url('vote', 'index');
        require $this->template;
    }

}